<?php
/**
 * User: Administrator
 * Note: 管理员角色--权限管理
 */
namespace Admin\Controller;

class AdminroleController extends BaseController
{
    public function index()
    {
        $_menu = M('menu')->where(array('pid'=>0))->field('id,name,css')->select();
        $this->assign('topmenu', $_menu);

        $auth = M('auth')->select();
        $this->assign('auth', $auth);

        $auth_group = M('auth_group')->select();
        $this->assign('auth_group', $auth_group);

        $member = M('member')->select();
        $this->assign('member', $member);
        $this->assign('meta_title', '角色管理');
        $this->display();
    }

    /**
     **页面注册
     * anthor:nyx
     */
    public function addPageRole()
    {
        $name  = I('name', '', 'trim');
        $auth  = I('auth', '', 'trim');
        $pid   = I('pid', '', 'trim');
        $child = I('child', '', 'trim');
        $auth_group = I('au', '', 'trim');
        $sort = I('sort', '', 'trim');
        if (M('auth')->where(array('name'=>$name))->find()) {
            appReturn(0, '该页面注册名称已使用');
        }
        if (M('auth')->where(array('auth'=>$auth))->find()) {
            appReturn(0, '该链接地址已使用');
        }
        $model = M();
        $model->startTrans();
        //当父级为根目录时
        if ($pid === '0') {
            //添加菜单
            $a = $model->table('tp_menu')->add(array(
                'name' => $name,
                'url'  => $auth,
                'pid'  => $pid,
                'sort' => $sort
            ));
            foreach ($auth_group as $k=>$v) {
                if ($v == 'on') {
                    $ge = $model->table('tp_auth_group')->where(array('id'=>$k))->find();
                    $menu_ids = explode(',', $ge['menu_ids']);
                    array_push($menu_ids, $a);
                    $menu_ids = array_unique($menu_ids);

                    $ge['menu_ids'] = implode(',', $menu_ids);
                    unset($ge['id']);
                    $auth = $model->table('tp_auth_group')->where(array('id'=>$k))->save($ge);
                }
            }

            if ($a && $ge) {
                $model->commit();
                appReturn(1, '页面注册成功');
            }
        }
        if ($au =$model->table('tp_auth')->add(array(
            'name' => $name,
            'auth' => $auth,
        ))) {
            //如果$child为空，则加入的是一个菜单项，不为空，则不加入到菜单项中
            if (!$child) {
                //添加菜单
                $me = $model->table('tp_menu')->add(array(
                    'name' => $name,
                    'url'  => $auth,
                    'pid'  => $pid,
                    'sort' => $sort
                ));
                //添加auth表中的mid和pid字段
                $pau = M('auth')->where(array('id'=>$au))->save(array('pid'=>$pid,'mid'=>$me));
                if (!($me && $pau)) {
                    $model->rollback();
                    appReturn(0, '页面注册失败');
                }


                //遍历权限角色列表
                foreach ($auth_group as $k=>$v) {
                    if ($v == 'on') {
                        $g = $model->table('tp_auth_group')->where(array('id'=>$k))->find();
                        $auth_ids = explode(',', $g['auth_ids']);
                        array_push($auth_ids, $au);
                        $auth_ids = array_unique($auth_ids, SORT_NUMERIC);
                        $menu_ids = explode(',', $g['menu_ids']);
                        array_push($menu_ids, $me);
                        $menu_ids = array_unique($menu_ids, SORT_NUMERIC);

                        $g['menu_ids'] = implode(',', $menu_ids);
                        $g['auth_ids'] = implode(',', $auth_ids);
                        unset($g['id']);
                        $auth = $model->table('tp_auth_group')->where(array('id'=>$k))->save($g);
                    }
                }

                if ($auth && $me && $au) {
                    $model->commit();
                    appReturn(1, '页面注册成功');
                } else {
                    $model->rollback();
                    appReturn(0, '页面注册失败');
                }
            } else {
                //添加auth表中的mid和pid字段
                $pau = M('auth')->where(array('id'=>$au))->save(array('pid'=>$pid,'mid'=>$child));
                if (!$pau) {
                    $model->rollback();
                    appReturn(0, '页面注册失败');
                }

                //遍历权限角色列表
                foreach ($auth_group as $k=>$v) {
                    if ($v == 'on') {
                        $g = $model->table('tp_auth_group')->where(array('id'=>$k))->find();
                        $auth_ids = explode(',', $g['auth_ids']);
                        array_push($auth_ids, $au);
                        $auth_ids = array_unique($auth_ids, SORT_NUMERIC);

                        $g['auth_ids'] = implode(',', $auth_ids);
                        unset($g['id']);
                        $auth = $model->table('tp_auth_group')->where(array('id'=>$k))->save($g);
                    }
                }
                if ($auth && $au) {
                    $model->commit();
                    appReturn(1, '页面注册成功');
                } else {
                    $model->rollback();
                    appReturn(0, '页面注册失败');
                }
            }
        }
    }

    public function get_second()
    {
        if (IS_POST) {
            $id = I('id', '', 'trim');
            if ($id > 0) {
                $child = M('menu')->where(array('pid'=>$id,'scene'=>0))->field('id,name')->select();
                if ($child) {
                    appReturn(1, '', $child);
                }
            }
        }
    }
    // 改变状态启禁用删除
    public function changeStatus()
    {
        $method = I('method', '', 'trim');
        $ids    = I('ids');
        $map['id'] = array('IN',$ids);
        $map2['auth_group_id'] = array('IN',$ids);
        switch ($method) {
            case 'enable':
                $res = M('auth_group')->where($map)->save(array('status'=>1));
                if ($res === false) {
                    appReturn(0, '操作失败');
                } else {
                    appReturn(1, '操作成功');
                }
                break;
            case 'disable':
                $res = M('auth_group')->where($map)->save(array('status'=>0));
                if ($res === false) {
                    appReturn(0, '操作失败');
                } else {
                    appReturn(1, '操作成功');
                }
                break;
            case 'del':
                if (M('member')->where($map2)->where(array('is_del'=>0))->find()) {
                    appReturn(0, '操作失败，有管理员属于此角色，无法删除');
                }
                $res = M('auth_group')->where($map)->delete();
                if ($res === false) {
                    appReturn(0, '操作失败');
                } else {
                    appReturn(1, '操作成功');
                }
                break;
            default:
                appReturn(0, '参数错误');
        }
    }


    /**
     **权限列表管理
     * anthor:nyx
     */
    public function manage()
    {
        if (IS_POST) {
            $page_count = I('limit', '', 'intval');
            $page  = I('page', '', 'intval');
            $total = M('auth_group')->count();
            $limit = ($page - 1)*$page_count.','.$page_count;
            $_list = M('auth_group')
                ->limit($limit)
                ->order('id asc')
                ->select();
            layuiReturn(0, '成功', $_list, $total);
        } else {
            $this->assign('meta_title', '权限列表管理');
            $this->display();
        }
    }


    /**
     **后团管理员权限编辑页面展示
     * anthor:nyx
     */
    public function edit()
    {
        $id = I('id', 0, 'intval');
        if (!$id) {
            $this->error('参数错误', U('Adminrole/index'));
        }
        $auth  = M('auth')->where(array('scene'=>0))->field('id,pid,mid,name')->select();
        $_menu = M('menu')->where(array('scene'=>0,'pid'=>0))->field('id,pid,name')->select();
        $_menu_child = M('menu')->where(array('scene'=>0,'pid'=>array('gt',0)))->field('id,pid,name')->select();
        $info = M('auth_group')->where(array('id'=>$id))->find();
        if (!$info) {
            $this->error('参数错误', U('User/index'));
        }
        $info['auth_ids'] = explode(',', $info['auth_ids']);
        $info['menu_ids'] = explode(',', $info['menu_ids']);

        $this->assign('auth', $auth);
        $this->assign('menu_child', $_menu_child);
        $this->assign('menu', $_menu);
        $this->assign('info', $info);
        $this->assign('meta_title', '修改权限列表');
        $this->display();
    }


    /**
     **添加角色
     * anthor:nyx
     */
    public function add()
    {
        if (IS_POST) {
            $name = I('name', '', 'trim');
            if (M('auth_group')->add(array('name'=>$name))) {
                appReturn(1, '添加权限标题成功');
            } else {
                appReturn(0, '添加权限标题失败');
            }
        } else {
            $this->assign('meta_title', '添加角色');
            $this->display();
        }
    }


    /**
     **改变角色权限内容
     * anthor:nyx
     */
    public function changeRole()
    {
        $id     = I('id', '', 'trim');
        $type   = I('type', '', 'trim');
        $status = I('status', '', 'trim');
        if (strstr($type, 'auth')) {
            $type = trim($type, 'auth[]');
            if ($status == 'true') {
                $auth = M('auth_group')->where(array('id'=>$id))->find();
                $auth['auth_ids'] = explode(',', $auth['auth_ids']);
                while ($key = array_search($type, $auth['auth_ids'])) {
                    array_splice($auth['auth_ids'], $key, 1);
                }
                $auth['auth_ids'][] = $type;
                $auth['auth_ids']   = implode(",", $auth['auth_ids']);
            } elseif ($status == 'false') {
                $auth = M('auth_group')->where(array('id'=>$id))->find();
                $auth['auth_ids'] = explode(',', $auth['auth_ids']);
                while ($key = array_search($type, $auth['auth_ids'])) {
                    array_splice($auth['auth_ids'], $key, 1);
                }

                $auth['auth_ids']=implode(",", $auth['auth_ids']);
            }
        } elseif (strstr($type, 'menu')) {
            $type = trim($type, 'menu[]');

            $auth = M('auth_group')->where(array('id'=>$id))->find();
            $auth_menu = M('auth')->where(array('pid'=>$type))->field('id')->select();
            $menu = M('menu')->where(array('pid'=>$type))->field('id')->select();

            $auth_menus = $menus = array();
            foreach ($auth_menu as $a) {
                $auth_menus[] = $a['id'];
            }
            foreach ($menu as $m) {
                $menus[] = $m['id'];
            }
            $menus[] = $type;
            $auth['auth_ids'] = explode(',', $auth['auth_ids']);
            $auth['menu_ids'] = explode(',', $auth['menu_ids']);
            if ($status == 'true') {
                $auth['menu_ids'] = array_merge($auth['menu_ids'], $menus);
                $auth['menu_ids'] = array_unique($auth['menu_ids'], SORT_NUMERIC);
                $auth['auth_ids'] = array_merge($auth['auth_ids'], $auth_menus);
                $auth['auth_ids'] = array_unique($auth['auth_ids'], SORT_NUMERIC);
            } elseif ($status == 'false') {
                $auth['auth_ids'] = array_diff($auth['auth_ids'], $auth_menus);
                $auth['menu_ids'] = array_diff($auth['menu_ids'], $menus);
            }
            $auth['menu_ids'] = implode(",", $auth['menu_ids']);
            $auth['auth_ids'] = implode(",", $auth['auth_ids']);
        } elseif (strstr($type, 'child')) {
            $type = trim($type, 'child[]');

            $auth = M('auth_group')->where(array('id'=>$id))->find();
            $auth_menu = M('auth')->where(array('mid'=>$type))->field('id')->select();
            $menu = M('menu')->where(array('id'=>$type))->field('id')->find();

            $auth_menus = $menus = array();
            foreach ($auth_menu as $a) {
                $auth_menus[] = $a['id'];
            }
            $menus[] = $menu['id'];

            $auth['auth_ids'] = explode(',', $auth['auth_ids']);
            $auth['menu_ids'] = explode(',', $auth['menu_ids']);
            if ($status == 'true') {
                $auth['menu_ids'] = array_merge($auth['menu_ids'], $menus);
                $auth['menu_ids'] = array_unique($auth['menu_ids'], SORT_NUMERIC);
                $auth['auth_ids'] = array_merge($auth['auth_ids'], $auth_menus);
                $auth['auth_ids'] = array_unique($auth['auth_ids'], SORT_NUMERIC);
            } elseif ($status == 'false') {
                $auth['auth_ids'] = array_diff($auth['auth_ids'], $auth_menus);
                $auth['menu_ids'] = array_diff($auth['menu_ids'], $menus);
            }
            $auth['menu_ids']= implode(",", $auth['menu_ids']);
            $auth['auth_ids']= implode(",", $auth['auth_ids']);
        }
        unset($auth['id']);

        if (M('auth_group')->where(array('id'=>$id))->save($auth)) {
            appReturn(1, '操作成功');
        } else {
            appReturn(1, '操作成功');
        }
    }


    /**
     **后台管理员用户管理
     * anthor:nyx
     */
    public function member()
    {
        if (IS_POST) {
            $username   = I('username', '', 'trim');
            $page_count = I('limit', '', 'intval');
            $page = I('page', '', 'intval');
            $map  = array();
            if ($username) {
                $map['username'] = array('like', '%'.$username.'%');
            }
            $map['is_del'] = '0';

            $total = M('member')->where($map)->count();
            $limit = ($page - 1)*$page_count.','.$page_count;
            $_list = M('member')->alias('m')
                ->join("LEFT JOIN tp_auth_group a on a.id = m.auth_group_id")
                ->field(array('m.id'=>'mid','m.*','a.name'))
                ->limit($limit)
                ->order('m.id desc')
                ->where($map)
                ->select();
            layuiReturn(0, '成功', $_list, $total);
        } else {
            $this->assign('meta_title', '后台用户管理');
            $this->display();
        }
    }

    /**
     **后台管理员用户编辑
     * anthor:nyx
     */
    public function memedit()
    {
        if (IS_POST) {
            $id = I('id', '', 'intval');
            $auth_group = I('auth_group', '', 'trim');
            if (M('member')->where(array('id'=>$id))->save(array('auth_group_id'=>$auth_group))) {
                appReturn(1, '编辑管理员成功');
            } else {
                appReturn(0, '编辑管理员失败');
            }
        } else {
            $id = I('id', '', 'intval');
            if (!$id) {
                $this->error('参数错误', U('Adminrole/index'));
            }

            $info = M('member')->where(array('id'=>$id))->find();
            if (!$info) {
                $this->error('参数错误', U('Adminrole/index'));
            }
            $auth = M('auth_group')->select();
            $this->assign('auth', $auth);
            $this->assign('info', $info);
            $this->assign('meta_title', '编辑管理员信息');
            $this->display();
        }
    }


    /**
     **后台管理员用户状态，启禁用删除
     * anthor:nyx
     */
    public function memchangeStatus()
    {
        $method = I('method', '', 'trim');
        $ids    = I('ids');
        $map['id'] = array('IN',$ids);
        switch ($method) {
            case 'enable':
                $res = M('member')->where($map)->save(array('status'=>1));
                if ($res === false) {
                    appReturn(0, '操作失败');
                } else {
                    appReturn(1, '操作成功');
                }
                break;
            case 'disable':
                $res = M('member')->where($map)->save(array('status'=>0));
                if ($res === false) {
                    appReturn(0, '操作失败');
                } else {
                    appReturn(1, '操作成功');
                }
                break;
            case 'del':
                $res = M('member')->where($map)->save(array('is_del'=>1));
                if ($res === false) {
                    appReturn(0, '操作失败');
                } else {
                    appReturn(1, '操作成功');
                }
                break;
            default:
                appReturn(0, '参数错误');
        }
    }


    /**
     **添加后台管理员
     * anthor:nyx
     */
    public function addmem()
    {
        if (IS_POST) {
            $username   = I('username', '', 'trim');
            $auth_group = I('auth_group', '', 'trim');
            $salt = 'nyx';
            if (M('member')->add(array('username'=>$username,'password'=>md5('12345678'.$salt),'auth_group_id'=>$auth_group))) {
                appReturn(1, '添加管理员成功');
            } else {
                appReturn(0, '添加管理员失败');
            }
        } else {
            $auth = M('auth_group')->field('id,name')->select();
            $this->assign('auth', $auth);
            $this->display();
        }
    }

    /**
     **将管理员用户密码重置为默认密码
     * anthor:nyx
     */
    public function resetpassword()
    {
        $id = I('id', '', 'intval');
        if (!$id) {
            $this->error('参数错误', U('Adminrole/index'));
        }
        $salt = 'nyx';
        if (M('member')->where(array('id'=>$id))->save(array('password'=>md5('12345678'.$salt)))) {
            appReturn(1, '重置管理员密码成功');
        } else {
            appReturn(0, '重置管理员密码失败');
        }
    }
}
